package com.jhs.demo.dragrecy;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jhs.demo.R;

import java.util.Collections;
import java.util.List;

/**
 * Created by wangqi on 2018/7/31.
 */
public class SimpleRecycleAdapter extends RecyclerView.Adapter<SimpleRecycleAdapter.SimpleViewHolder> implements SimpleItemTouchListener {

    private List<String> mList;
    private Context mContext;

    public SimpleRecycleAdapter(Context mContext) {
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public SimpleViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new SimpleViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_simple_touch_view,viewGroup,false));
    }

    @Override
    public void onBindViewHolder(@NonNull SimpleViewHolder simpleViewHolder, int position) {
        simpleViewHolder.itemTv.setText(mList.get(position));
    }

    @Override
    public int getItemCount() {
        return mList==null?0:mList.size();
    }

    class SimpleViewHolder extends RecyclerView.ViewHolder{

        TextView itemTv;

        public SimpleViewHolder(@NonNull View itemView) {
            super(itemView);
            itemTv = itemView.findViewById(R.id.item_tv);
        }
    }

    @Override
    public void onItemDrag(int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                Collections.swap(mList, i, i + 1);
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                Collections.swap(mList, i, i - 1);
            }
        }
        notifyItemMoved(fromPosition,toPosition);
    }

    @Override
    public void onItemDelete(int position) {
        mList.remove(position);
        notifyItemRemoved(position);
    }

    public void setData(List<String> mList) {
        this.mList = mList;
        notifyDataSetChanged();
    }
}
